package com.kfgj.hkp.common.components.http;

import com.kfgj.hkp.common.components.io.AutoExtendByteBuffer;
import org.apache.http.*;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * Created by liwensihan on 2015/1/15.
 *
 * @author liwensihan
 */
public class HttpHelper {


    private static CloseableHttpClient httpClient = null;

    private static CloseableHttpClient getClient(){
        if (httpClient==null){
            httpClient = HttpClients.createDefault();
        }
        return httpClient;
    }

    public static String getRequest(String uri) {
        String result = null;
        try {
            HttpGet httpGet = new HttpGet(uri);
            HttpResponse response = getClient().execute(httpGet);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                long len = entity.getContentLength();
                len = len > 0 ? len : 1024 * 1024;
                InputStream instream = entity.getContent();
                AutoExtendByteBuffer buffer = new AutoExtendByteBuffer();
                int l;
                byte[] tmp = new byte[2048];
                while ((l = instream.read(tmp)) != -1) {
                    buffer.append(tmp, 0, l);
                }
                byte[] bt = buffer.getBytes();
                result = new String(bt, Charset.forName(getCharset(entity.getContentType(), "GBK"))).trim();
            }
        } catch (IOException e) {
            throw new HttpRequestException(String.format("请求发生异常，地址为：%s",uri));
        }

        return result;
    }

    public static String getCharset(Header header, String def) {
        HeaderElement[] hes = header.getElements();
        for (int i = 0; i < hes.length; i++) {
            HeaderElement he = hes[i];
            NameValuePair[] nvps = he.getParameters();
            for (int j = 0; j < nvps.length; j++) {
                NameValuePair nvp = nvps[j];
                if ("charset".equalsIgnoreCase(nvp.getName())) {
                    return nvp.getValue();
                }
            }
        }
        return def;
    }

}
